//
//  SeedAlgorithmMgr.m
//  SKStock
//
//  Created by thPark on 11. 3. 2..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SeedAlgorithmMgr.h"

// Round keys for encryption or decryption
DWORD pSeedRoundKey[32];													
// User secret key
BYTE pSeedKey[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 		
	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

@implementation SeedAlgorithmMgr


+ (char*)seedEncryption:(NSString*)str{
	
	char* inStr = (char*)[str UTF8String];
	size_t strLen = strlen(inStr);
	
	
	double blocks = strLen/16.0f;
	
	int size;
	if((int) blocks < blocks) {
		size = ((int) blocks + 1) * 16;
	}else{
		size = ((int) blocks) * 16;
	}
	
	
	char *seedStr = (char*)malloc(size);
	
	
	BYTE tmp[16] = {0x00};
	
	SeedRoundKey(pSeedRoundKey, pSeedKey);
	
	int i=0, j=0, k=0;
	while(i<blocks){
		
		for(j=0; j<16; j++) tmp[j] = ((i*16)+j > (int)strLen) ? 0x00 : inStr[(i*16)+j];
		
		SeedEncrypt(tmp, pSeedRoundKey);
		
		for(k=0; k<16; k++) seedStr[(i*16)+k] = tmp[k];
		
		i++;
	}
	
	char *encodedTxt;
	[self base64_encode:seedStr numBytes:size encodedText:&encodedTxt];
	if(seedStr)
		free(seedStr);

	return encodedTxt;
	
	
	
	
	//	unsigned char* pSeedData = (unsigned char*)[str UTF8String];
//	NSLog(@"SEED LEN BEFOR===================> %d",strlen((const char*)pSeedData));
//
//	
//	
//	
//	SeedRoundKey(pSeedRoundKey, pSeedKey);
//	SeedEncrypt(pSeedData, pSeedRoundKey);
//	
//	
//	NSLog(@"SEED LEN AFTER1===================> %d",strlen((const char*)pSeedData));
//	
//	
//	/*
//	printf ("SeedEncrypt  : ");
//	for (int i=0;i<strlen(pSeedData);i++)	
//		printf("%02X ",pSeedData[i]);
//	printf("\n");
//	*/
//	
//	unsigned char* result = malloc(strlen((const char*)pSeedData));
//	//memset(result,0x00,strlen((const char*)pSeedData));
//	memcpy(result, pSeedData, strlen((const char*)pSeedData));
//	return result;
	
}

+ (NSString*)seedDecryption:(char*)pSeedData{
	
	
	size_t strLen = strlen(pSeedData);
	
	unsigned char *dst = (unsigned char*)malloc(strLen+100);
	int len_b64 = [self base64_decode:pSeedData dst:dst numBytes:strLen+100 ];

	char* b64decoded_text = (char*)malloc(len_b64);
	memset(b64decoded_text,'\0',len_b64);
	
	BYTE tmp[16] = {0x00};
	
	SeedRoundKey(pSeedRoundKey, pSeedKey);
	
	
	int i=0, j=0, k=0;
	for(i=0; i<strLen; i++){
		if(i>0 && (i%16)==0) {
			SeedDecrypt(tmp, pSeedRoundKey);
			for(j=0; j<16; j++) {
				b64decoded_text[(k*16)+j] = tmp[j];
			}
			k++;
		}
		tmp[i%16] = dst[i];
	}
	
	
	NSString* strResult = [NSString stringWithUTF8String:b64decoded_text];
	if(b64decoded_text) free(b64decoded_text);
	return strResult;
	
	
	
	//	unsigned char* tempData = malloc(strlen((const char*)pSeedData));
//	memset(tempData,0x00,strlen((const char*)pSeedData));
//	memcpy(tempData, pSeedData, strlen((const char*)pSeedData));
//	NSLog(@"SEED LEN AFTER2===================> %d",strlen((const char*)tempData));
//	SeedRoundKey(pSeedRoundKey, pSeedKey);
//	SeedDecrypt(tempData, pSeedRoundKey);
//	
//	NSLog(@"SEED LEN FINAL===================> %d\n\n\n\n\n\n",strlen((const char*)tempData));
//	
//	/*
//	printf ("SeedDecrypt  : ");
//	for (int i=0;i<strlen(pSeedData);i++)	
//		printf("%02X ",pSeedData[i]);
//	printf("\n");
//	*/
//	NSString* strResult = [NSString stringWithCString:(const char*)tempData encoding:NSUTF8StringEncoding];
//	//NSLog(@"######### seedDecryption : [%@]", strResult);
//	//free(tempData);
//	return strResult;
}


+(int)base64_encode:(char*)text numBytes:(int)numBytes encodedText:(char**)encodedText
{
	const char MimeBase64[] = {
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
		'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
		'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
		'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
		'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
		'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
		'w', 'x', 'y', 'z', '0', '1', '2', '3',
		'4', '5', '6', '7', '8', '9', '+', '/'
	};
	
	unsigned char input[3]  = {0,0,0};
	unsigned char output[4] = {0,0,0,0};
	int   index, i, j, size;
	char *p, *plen;
	plen           = text + numBytes - 1;
	size           = (4 * (numBytes / 3)) + (numBytes % 3? 4 : 0) + 1;
	(*encodedText) = (char*)malloc(size);
	j              = 0;
    for  (i = 0, p = text;p <= plen; i++, p++) {
        index = i % 3;
        input[index] = *p;
        if (index == 2 || p == plen) {
            output[0] = ((input[0] & 0xFC) >> 2);
            output[1] = ((input[0] & 0x3) << 4) | ((input[1] & 0xF0) >> 4);
            output[2] = ((input[1] & 0xF) << 2) | ((input[2] & 0xC0) >> 6);
            output[3] = (input[2] & 0x3F);
            (*encodedText)[j++] = MimeBase64[output[0]];
            (*encodedText)[j++] = MimeBase64[output[1]];
            (*encodedText)[j++] = index == 0? '=' : MimeBase64[output[2]];
            (*encodedText)[j++] = index <  2? '=' : MimeBase64[output[3]];
            input[0] = input[1] = input[2] = 0;
        }
    }
    (*encodedText)[j] = '\0';
    return size;
}



+(int)base64_decode:(const char*)text dst:(unsigned char*)dst numBytes:(int)numBytes
{
	int DecodeMimeBase64[256] = {
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
		52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
		-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
		15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
		-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
		41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
		-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
	};
	
	
	const char* cp;
	int space_idx = 0, phase;
	int d, prev_d = 0;
	unsigned char c;
    space_idx = 0;
    phase = 0;
    for ( cp = text; *cp != '\0'; ++cp ) {
        d = DecodeMimeBase64[(int) *cp];
        if ( d != -1 ) {
            switch ( phase ) {
                case 0:
                    ++phase;
                    break;
                case 1:
                    c = ( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) );
                    if ( space_idx < numBytes )
                        dst[space_idx++] = c;
                    ++phase;
                    break;
                case 2:
                    c = ( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) );
                    if ( space_idx < numBytes )
                        dst[space_idx++] = c;
                    ++phase;
                    break;
                case 3:
                    c = ( ( ( prev_d & 0x03 ) << 6 ) | d );
                    if ( space_idx < numBytes )
                        dst[space_idx++] = c;
                    phase = 0;
                    break;
            }
            prev_d = d;
        }
    }
    return space_idx;
}


@end


